package com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.impl;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.contour_setting;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.fly_path;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.potential_points;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warn_signal_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.reservoir_water_info;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ResultObj;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.SmallScaleSearch;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxSmallScaleService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("QxssService")
public class QxSmallScaleServiceImpl implements IQxSmallScaleService {
    @Resource
    private ITransformService iTransformService;

    ProcessRequestController pc = new ProcessRequestController();
    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();
    @Override
    public Date getScaleNewDate() {
        // TODO 获取最新实况数据
        Date date = new Date();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(observtime,'yyyy-MM-dd HH24:MI:SS') as observtime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam(String.format("city like '%s%%' ", DbConfig.CITY));
        selectRequest.setSort(new String[]{"observtime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            date = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            }).get(0).getObservtime();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return date;
    }

    @Override
    public List<ActualData> qxElementQuery(ActualElemQuery elemQuery) {
        // TODO 气象要素统计
        List<ActualData> resultList = new ArrayList<>();
        List<MsgMediumSmallScale> dataList = new ArrayList<>();
        Map<String, String> selectParam = new HashMap<>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String element = elemQuery.getElement();
        String type = elemQuery.getType();
        Date startDate = elemQuery.getStartDate();
        Date endDate = elemQuery.getEndDate();
        List<String> countys = elemQuery.getCountys();
        List<String> stations = elemQuery.getStations();
        String stationid = elemQuery.getStationid();
        String rainFilter = elemQuery.getRainFilter();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("observTime >='%tF %tT'", startDate, startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and observTime <='%tF %tT'", endDate, endDate));
        }
        if (countys != null && countys.size() > 0) {
            strWhere.append(" and county in (");
            String tempString = "";
            for (String county : countys) {
                tempString += String.format("'%s',", county);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        if (stations != null && stations.size() > 0) {
            strWhere.append(" and stationId in (");
            String tempString = "";
            for (String station : stations) {
                tempString += String.format("'%s',", station);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        if (stationid != null && stationid.length() > 0) {
            strWhere.append(" and stationId in (");
            String tempString = "";
            tempString += String.format("'%s',", stationid);
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns.add("stationname");
        columns.add("longitude");
        columns.add("latitude");
        if (element != null && element.equals("rain") ) {
            // 雨量和统计
            if (type != null && type.equals("sum")) {
                columns.add("sum(rain) as value");
                selectRequest.setSort(new String[]{"value desc"});
                strWhere.append(" and rain <> -65535");
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("sum(rain) as value");
                    strWhere.append(" and rain <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("rain");
                    strWhere.append(" and rain <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }else{
            if (type != null && type.equals("sum")) {
                //columns.add("sum(rain) as value");
                selectRequest.setSort(new String[]{"value desc"});
                strWhere.append(" and rain <> -65535");
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("sum(rain) as value");
                    strWhere.append(" and rain <> -65535 ");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("rain");
                    strWhere.append(" and rain <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("temp")) {
            // 温度统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add("cast(" + type + "(cast(DryBulbTemp as numeric(18,1))) as FLOAT) as value");
                strWhere.append(" and DryBulbTemp <> -65535");
                selectRequest.setSort(new String[]{"value desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(DryBulbTemp) as value");
                    strWhere.append(" and DryBulbTemp <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("DryBulbTemp");
                    strWhere.append(" and DryBulbTemp <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("winds")) {
            // 风速统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add(type + "(InstantWindV) as value");
                columns.add("instantwindd");
                strWhere.append(" and InstantWindV <> -65535");
                strWhere.append(" and instantwindd <> -65535");
                selectRequest.setSort(new String[]{"value desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(InstantWindV) as value");
                    strWhere.append(" and InstantWindV <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("InstantWindV");
                    strWhere.append(" and InstantWindV <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("humid")) {
            // 湿度统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add("cast(" + type + "(RelHumidity) as integer) as value");
                strWhere.append(" and RelHumidity <> -65535");
                selectRequest.setSort(new String[]{"value desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("cast(avg(RelHumidity)as integer) as value");
                    strWhere.append(" and RelHumidity <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("RelHumidity");
                    strWhere.append(" and RelHumidity <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("pressure")) {
            // 气压统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add(type + "(StationPress) as value");
                strWhere.append(" and StationPress <> -65535");
                selectRequest.setSort(new String[]{"value desc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(StationPress) as value");
                    strWhere.append(" and StationPress <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("StationPress");
                    strWhere.append(" and StationPress <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        if (element != null && element.equals("visibility")) {
            // 能见度统计
            if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
                columns.add(type + "(visibility) as value");
                strWhere.append(" and visibility <> -65535");
                selectRequest.setSort(new String[]{"value asc"});
            }
            // 表格统计
            if (type != null && (type.equals("spline") || type.equals("column"))) {
                if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                    columns.add("to_char(observtime,'yyyy-MM-dd') as datechar");
                    columns.add("avg(visibility) as value");
                    strWhere.append(" and visibility <> -65535");
                    selectRequest.setSort(new String[]{"to_char(observtime,'yyyy-MM-dd')"});
                } else {
                    columns.add("observtime");
                    columns.add("visibility");
                    strWhere.append(" and visibility <> -65535");
                    selectRequest.setSort(new String[]{"observtime"});
                }
            }
        }
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            if (DateTime.UserMainDataTable(elemQuery.getStartDate(), DbConfig.CACHEDAYS)) {
                selectParam.put("method", "msgmediumsmallscale");
            } else {
                selectParam.put("method", "msgmediumsmallscale");
            }
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<MsgMediumSmallScale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        // 赋值
        try {
            WebCtrlData webCtrlData = new WebCtrlData();
            if (dataList.size() > 0) {
                for (MsgMediumSmallScale data : dataList) {
                    ActualData actualData = new ActualData();
                    actualData.setStationId(data.getStationid().trim());
                    actualData.setStationName(data.getStationname().trim());
                    actualData.setLon(data.getLongitude());
                    actualData.setLat(data.getLatitude());

                    DmMapPoint dt = iTransformService.LonLatConvertToLambert(data.getLongitude(), data.getLatitude());
                    actualData.setX(dt.x);
                    actualData.setY(dt.y);
                    switch (element) {
                        case "rain":
                            //actualData.setRain(Double.parseDouble(String.format("%.1f", data.getValue())));
                            actualData.setValue(data.getValue());
                            actualData.setType("雨量");  // 设置 type 为 "雨量"
                            break;
                        case "temp":
                            //actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getValue())));
                            actualData.setValue(data.getValue());
                            actualData.setType("温度");  // 设置 type 为 "温度"
                            break;
                        case "humid":
                            //actualData.setHumid(Double.parseDouble(String.format("%d", data.getValue())));
                            actualData.setValue(data.getValue());
                            actualData.setType("湿度");  // 设置 type 为 "湿度"
                            break;
                        case "winds":
                            //actualData.setWinds(Double.parseDouble(String.format("%.1f", data.getValue())));
                            actualData.setValue(data.getValue());
                            actualData.setType("风速");  // 设置 type 为 "风速"
                            if (type != null && (type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max"))) {
                                String s = webCtrlData.GetAllFx(data.getValue().toString());
                                actualData.setWinddirect(s);
                                int i = webCtrlData.FengSuToFengJi(data.getValue());
                                actualData.setWindvelocity(i);
                            }
                            break;
                        case "pressure":
                            //actualData.setPressure(Double.parseDouble(String.format("%.1f", data.getValue())));
                            actualData.setValue(data.getValue());
                            actualData.setType("气压");  // 设置 type 为 "气压"
                            break;
                        case "visibility":
                            //    actualData.setVisibility(Double.parseDouble(String.format("%.1f", data.getValue()));
                            actualData.setValue(data.getValue());
                            actualData.setType("能见度");  // 设置 type 为 "能见度"
                            break;
                        default:
                            break;
                    }
                    if (elemQuery.getDaytype() != null && elemQuery.getDaytype().contains("日均")) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        actualData.setDateTime(sdf.parse(data.getDatechar()));
                    } else {
                        actualData.setDateTime(data.getObservtime());
                    }
                    resultList.add(actualData);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }

    @Override
    public List<MediumSmallScale> getPoint(SmallScaleSearch smallscalesearch) {
        // TODO 获取整点雨量、温度、湿度、风速、气压
        List<msgmediumsmallscale> listData = new ArrayList<msgmediumsmallscale>();
        List<MediumSmallScale> resultList = new ArrayList<MediumSmallScale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        List<String> countys = smallscalesearch.getCountys();
        columns.add("observTime");
        columns.add("StationID");
        columns.add("StationName");
        columns.add("Longitude");
        columns.add("Latitude");
        columns.add("rain");
        columns.add("CAST(replace(cast(DryBulbTemp AS VARCHAR),'-65535','99999') as float) as dryBulbTemp");
        columns.add("CAST(replace(cast(InstantWindV AS VARCHAR),'-65535','99999') as float) as instantWindV");
        columns.add("CAST(replace(cast(instantwindd AS VARCHAR),'-65535','99999') as integer) as instantwindd");
        columns.add("cast(replace(cast(RelHumidity AS VARCHAR),'-65535','99999') as integer) as relHumidity");
        columns.add("CAST(replace(cast(PressureSea AS VARCHAR),'-65535','99999') as float) as pressureSea");
        columns.add("CAST(replace(cast(visibility AS VARCHAR),'-65535','99999') as integer) as visibility");
        columns.add("City");
        columns.add("County");
        //columns.add("country");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        selectRequest.setSort(new String[]{"StationID asc"});
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (smallscalesearch.getObservTime() != null) {
            strWhere.append(String.format(" dateChar='%tF'", smallscalesearch.getObservTime()));
            whereCount++;
        }
        if (smallscalesearch.getStartDate() != null) {
            strWhere.append(String.format(" and observTime='%s'", smallscalesearch.getStartDate()+":00:00"));
        }
        if (!StringUtil.IsNullOrEmpty(smallscalesearch.getStationID())) {
            strWhere.append(String.format(" and StationID='%s'", smallscalesearch.getStationID()));
        }
        if (!StringUtil.IsNullOrEmpty(smallscalesearch.getType())) {
            strWhere.append(String.format(" and stationname='%s'", smallscalesearch.getType()));
        }
        if (countys != null && countys.size() > 0) {
            strWhere.append(" and county in (");
            String tempString = "";
            for (String county : countys) {
                tempString += String.format("'%s',", county);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        WebCtrlData webCtrlData=new WebCtrlData();
        if (listData != null && listData.size() > 0) {
            for (msgmediumsmallscale msg : listData) {
                MediumSmallScale smallscale = new MediumSmallScale();
                smallscale.setObservTime(msg.getObservtime());
                smallscale.setStationID(msg.getStationid());
                smallscale.setLongitude(msg.getLongitude());
                smallscale.setLatitude(msg.getLatitude());
                smallscale.setLon(msg.getLongitude());
                smallscale.setLat(msg.getLatitude());
                smallscale.setStationName(msg.getStationname());
                smallscale.setRain(msg.getRain());
                smallscale.setDryBulbTemp(msg.getDrybulbtemp());
                smallscale.setInstantWindV(msg.getInstantwindv());
                String s = webCtrlData.GetAllFx(msg.getInstantwindd().toString());
                smallscale.setFX(s);
                smallscale.setRelHumidity(msg.getRelhumidity());
                smallscale.setPressureSea(msg.getPressuresea());
                smallscale.setCity(msg.getCity());
                smallscale.setCounty(msg.getCounty());
                smallscale.setVisibility(msg.getVisibility());
                resultList.add(smallscale);
            }
        }
        return resultList;
    }

    @Override
    public MediumSmallScale getHourRain(SmallScaleSearch smallscalesearch) {
        List<msgmediumsmallscale> listData = new ArrayList<msgmediumsmallscale>();
        MediumSmallScale smallscale = new MediumSmallScale();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("Longitude");
        columns.add("Latitude");
        columns.add("sum(rain) as rain");
        columns.add("StationName");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        selectRequest.setSort(new String[]{"sum(rain) desc"});
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (smallscalesearch.getStartDate() != null) {
            whereCount++;
            strWhere.append(String.format("observTime>='%s'", smallscalesearch.getStartDate()));
        }
        if (smallscalesearch.getEndDate() != null) {
            strWhere.append(String.format(" and observTime<='%s'", smallscalesearch.getEndDate()));
        }
        strWhere.append(" and city like '"+DbConfig.CITY+"%' ");
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (listData != null && listData.size() > 0) {
            BigDecimal b = new BigDecimal(listData.get(0).getRain());
            float f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
            smallscale.setLon(listData.get(0).getLongitude());
            smallscale.setLat(listData.get(0).getLatitude());
            smallscale.setStationName(listData.get(0).getStationname());
            smallscale.setRain(f1);
        }
        return smallscale;
    }


    /****
     * 获取七天城镇预报  两个地方用到 两天/七天
     * @param request
     * @return
     */
    @Override
    public Object getSevenForecast(HttpServletRequest request) {
        DateTime currentTime = DateTime.now();
        String strDate = currentTime.toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
        String strTime = "";
        if (currentTime.GetHour() >= 8 && currentTime.GetHour() < 20)
            strTime = "08";
        else if (currentTime.GetHour() >= 0 && currentTime.GetHour() < 8) {
            strDate = currentTime.AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            strTime = "20";
        } else {
            strTime = "20";
        }
        String NTimes = "24"; // 时效
        String county = request.getParameter("county"); // 所属县
        if (StringUtil.IsNullOrEmpty(county)) {
            county = DbConfig.COUNTY;
        }
        String result = "";
        try {
            WebCtrlData web = new WebCtrlData();
            RequestDataBySelect dataBySelect = new RequestDataBySelect();
            Map<String, String> map = new HashMap<String, String>();
            dataBySelect.setColumns(new String[]{"StationID , StationName ,city ,county ,"
                    + "DateChar ,TimeChar ,nTimes ,"
                    + "Longitude , Latitude , altitude ,"
                    + "Weather2 , Weather1 ,cast(MaxTemp As Decimal(10, 1)) , "
                    + "cast(MinTemp As Decimal(10, 1)) , Wind1 , Wind2 , "
                    + "WindD1 , WindD2 "});
            dataBySelect.setParam("DateChar = '" + strDate + "' AND TimeChar = '" + strTime + "' AND NTimes <= '" + NTimes + "' " + "and NTimes%12 = 0 and  county like '" + county + "%' ");
            dataBySelect.setSort(new String[]{"StationID"});
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "ForecastInfoTemp");
            map.put("sqlType", "select");
            String message = pc.processRequest(map);

            List<forecastinfotemp> forecast = new ArrayList<forecastinfotemp>();
            forecast = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forecastinfotemp>>() {
            });
            if (forecast != null && forecast.size() > 0) {
                result = "{\"message\": \"查询成功\",\n" +
                        "\"data\": [";
                for (forecastinfotemp temp : forecast) {
                    result += "{";
                    result += "\"stationId\":\"" + temp.getStationid() + "\",";
                    result += "\"stationName\":\"" + temp.getStationname().trim() + "\",";
                    result += "\"city\":\"" + temp.getCity().trim() + "\","; //
                    result += "\"county\":\"" + temp.getCounty().trim() + "\",";//
                    result += "\"forcastDate\":\"" + new DateTime(temp.getDatechar()).toDateString().trim() + "\",";
                    result += "\"forcastSc\":\"" + temp.getTimechar().trim() + "\",";
                    result += "\"forcastSx\":\"" + temp.getNtimes().toString().trim() + "\",";
                    String strMinTemp = temp.getMintemp().toString().trim();
                    String strMaxTemp = temp.getMaxtemp().toString().trim();
                    if (strMinTemp.equals("-65535.0") || strMinTemp.equals("65535.0")) {
                        strMinTemp = "";
                    }
                    if (strMaxTemp.equals("-65535.0") || strMaxTemp.equals("65535.0")) {
                        strMaxTemp = "";
                    }
                    result += "\"maxTemp\":\"" + strMaxTemp + "\",";
                    result += "\"minTemp\":\"" + strMinTemp + "\",";
                    //Wind1 AS 最小风速, Wind2 AS 最大风速, " + "WindD1 AS 最小风向, WindD2 AS 最大风向
                    String strWindDir1 = temp.getWind1().toString().trim();
                    String strWindDir2 = temp.getWind2().toString().trim();
                    strWindDir1 = WebCtrlData.GetAllFx(strWindDir1 == "-65535" ? "0" : strWindDir1).toString();
                    strWindDir2 = WebCtrlData.GetAllFx(strWindDir2 == "-65535" ? "0" : strWindDir2).toString();

                    if (!strWindDir1.equals(strWindDir2))
                        strWindDir1 = strWindDir1 + "转" + strWindDir2;
                    result += "\"windD\":\"" + strWindDir1 + "\","; //
                    String strMinWind = temp.getWindd1().toString().trim();
                    int minWind = Integer.parseInt(strMinWind == "-65535" ? "0" : strMinWind);
                    String minWindS = String.format("%02d", minWind);

                    String strMaxWind = temp.getWindd2().toString().trim();
                    int maxWind = Integer.parseInt(strMaxWind == "-65535" ? "0" : strMaxWind);
                    String maxWindS = String.format("%02d", maxWind);
                    String strWindDisp = "";
                    if (minWindS == maxWindS)
                        strWindDisp = web.GetWeatherFs(minWindS);
                    else
                        strWindDisp = web.GetWeatherFs(minWindS) + " 转 " + web.GetWeatherFs(maxWindS);
                    result += "\"windV\":\"" + strWindDisp + "\",";//
                    String strWeather1 = temp.getWeather1().toString().trim();
                    String strWeather2 = temp.getWeather2().toString().trim();
                    strWeather1 = String.format("%02d", Integer.parseInt(strWeather1 == "-65535" ? "0" : strWeather1));
                    strWeather2 = String.format("%02d", Integer.parseInt(strWeather2 == "-65535" ? "0" : strWeather2));
                    String strWeatherDisp = "";
                    if (strWeather1.equals(strWeather2))
                        strWeatherDisp = WebCtrlData.WeatherNameToPicPath(strWeather1);
                    else
                        strWeatherDisp = WebCtrlData.WeatherNameToPicPath(strWeather1) + "转"
                                + WebCtrlData.WeatherNameToPicPath(strWeather2);
                    result += "\"weatherCode1\":\"" + strWeather1 + "\",";
                    result += "\"weatherCode2\":\"" + strWeather2 + "\",";
                    result += "\"WeatherPhenomena\":\"" + strWeatherDisp + "\",";
                    //"Longitude AS 经度, Latitude AS 纬度, altitude as 海拔
                    result += "\"lon\":" + temp.getLongitude() + ",";
                    result += "\"lat\":" + temp.getLatitude() + ",";
                    DmMapPoint dt = iTransformService.LonLatConvertToLambert(temp.getLongitude() , temp.getLatitude());
                    result+="\"x\":" + dt.x+"" + ",";
                    result+="\"y\":" + dt.y+"" + ",";
                    result += "\"altitude\":\""
                            + Double.parseDouble(temp.getAltitude().toString() == "" ? "0" : temp.getAltitude().toString()) + "\"";
                    result += "},";
                }
                if (result.endsWith(","))
                    result = result.subSequence(0, result.length() - 1) + "],\"status\": 511025}";
                else
                    result = result + "],\"status\": 511025}";
            }
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return result;
    }

    @Override
    public Object getSevenTownForecast(HttpServletRequest request) {
        DateTime currentTime = DateTime.now();
        String strDate = currentTime.toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
        String strTime = "";
        if(currentTime.GetHour() >= 8 && currentTime.GetHour() < 20)
            strTime = "08";
        else if (currentTime.GetHour() >= 0 && currentTime.GetHour()<8){
            strDate = currentTime.AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            strTime = "20";
        } else{
            strTime = "20";
        }
        String NTimes = "168"; // 时效
        String stationid = request.getParameter("stationid"); // 所属县
        String datechar = request.getParameter("datechar");
        String time = request.getParameter("timechar");
        String result = "";

        try {
            WebCtrlData web = new WebCtrlData();
            RequestDataBySelect dataBySelect = new RequestDataBySelect();
            Map<String, String> map = new HashMap<String, String>();
            dataBySelect.setColumns(new String[]{"StationID , StationName ,city ,county ,"
                    + "DateChar ,TimeChar ,nTimes ,"
                    + "Longitude , Latitude , altitude ,"
                    + "Weather2 , Weather1 ,cast(MaxTemp As Decimal(10, 1)) , "
                    + "cast(MinTemp As Decimal(10, 1)) , Wind1 , Wind2 , "
                    + "WindD1 , WindD2 "});
            StringBuilder strWhere = new StringBuilder();
            int whereCount = 0;
            if (!StringUtil.IsNullOrEmpty(strDate)) {
                whereCount++;
                strWhere.append(String.format("DateChar ='%s'", strDate));
            }
            if (!StringUtil.IsNullOrEmpty(strTime)) {
                strWhere.append(String.format(" and Timechar ='%s'", strTime));
            }
            if (!StringUtil.IsNullOrEmpty(NTimes)) {
                strWhere.append(String.format(" and NTimes ='%s'", NTimes));
            }
            if (!StringUtil.IsNullOrEmpty(stationid)) {
                strWhere.append(String.format(" and stationid ='%s'", stationid));
            }
            if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
                strWhere = strWhere.replace(0, 4, "");
            }
            dataBySelect.setParam(strWhere.toString());
            dataBySelect.setSort(new String[]{"StationID"});
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "ForecastInfoTemp");
            map.put("sqlType", "select");
            String message = pc.processRequest(map);

            List<forecastinfotemp> forecast = new ArrayList<forecastinfotemp>();
            forecast = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forecastinfotemp>>() {
            });
            if (forecast != null && forecast.size() > 0) {
                result = "{\"message\": \"查询成功\",\n" +
                        "\"data\": [";
                for (forecastinfotemp temp : forecast) {
                    result += "{";
                    result += "\"stationId\":\"" + temp.getStationid() + "\",";
                    result += "\"stationName\":\"" + temp.getStationname().trim() + "\",";
                    result += "\"city\":\"" + temp.getCity().trim() + "\","; //
                    result += "\"county\":\"" + temp.getCounty().trim() + "\",";//
                    result += "\"forcastDate\":\"" + new DateTime(temp.getDatechar()).toDateString().trim() + "\",";
                    result += "\"forcastSc\":\"" + temp.getTimechar().trim() + "\",";
                    result += "\"forcastSx\":\"" + temp.getNtimes().toString().trim() + "\",";
                    String strMinTemp = temp.getMintemp().toString().trim();
                    String strMaxTemp = temp.getMaxtemp().toString().trim();
                    if (strMinTemp.equals("-65535.0") || strMinTemp.equals("65535.0")) {
                        strMinTemp = "";
                    }
                    if (strMaxTemp.equals("-65535.0") || strMaxTemp.equals("65535.0")) {
                        strMaxTemp = "";
                    }
                    result += "\"maxTemp\":\"" + strMaxTemp + "\",";
                    result += "\"minTemp\":\"" + strMinTemp + "\",";
                    //Wind1 AS 最小风速, Wind2 AS 最大风速, " + "WindD1 AS 最小风向, WindD2 AS 最大风向
                    String strWindDir1 = temp.getWind1().toString().trim();
                    String strWindDir2 = temp.getWind2().toString().trim();
                    strWindDir1 = WebCtrlData.GetAllFx(strWindDir1 == "-65535" ? "0" : strWindDir1).toString();
                    strWindDir2 = WebCtrlData.GetAllFx(strWindDir2 == "-65535" ? "0" : strWindDir2).toString();

                    if (!strWindDir1.equals(strWindDir2))
                        strWindDir1 = strWindDir1 + "转" + strWindDir2;
                    result += "\"windD\":\"" + strWindDir1 + "\","; //
                    String strMinWind = temp.getWindd1().toString().trim();
                    int minWind = Integer.parseInt(strMinWind == "-65535" ? "0" : strMinWind);
                    String minWindS = String.format("%02d", minWind);

                    String strMaxWind = temp.getWindd2().toString().trim();
                    int maxWind = Integer.parseInt(strMaxWind == "-65535" ? "0" : strMaxWind);
                    String maxWindS = String.format("%02d", maxWind);
                    String strWindDisp = "";
                    if (minWindS == maxWindS)
                        strWindDisp = web.GetWeatherFs(minWindS);
                    else
                        strWindDisp = web.GetWeatherFs(minWindS) + " 转 " + web.GetWeatherFs(maxWindS);
                    result += "\"windV\":\"" + strWindDisp + "\",";//
                    String strWeather1 = temp.getWeather1().toString().trim();
                    String strWeather2 = temp.getWeather1().toString().trim();
                    strWeather1 = String.format("%02d", Integer.parseInt(strWeather1 == "-65535" ? "0" : strWeather1));
                    strWeather2 = String.format("%02d", Integer.parseInt(strWeather2 == "-65535" ? "0" : strWeather2));
                    String strWeatherDisp = "";
                    if (strWeather1.equals(strWeather2))
                        strWeatherDisp = WebCtrlData.WeatherNameToPicPath(strWeather1);
                    else
                        strWeatherDisp = WebCtrlData.WeatherNameToPicPath(strWeather1) + "转"
                                + WebCtrlData.WeatherNameToPicPath(strWeather2);
                    result += "\"weatherCode1\":\"" + strWeather1 + "\",";
                    result += "\"weatherCode2\":\"" + strWeather2 + "\",";
                    result += "\"WeatherPhenomena\":\"" + strWeatherDisp + "\",";
                    //"Longitude AS 经度, Latitude AS 纬度, altitude as 海拔
                    result += "\"lon\":" + temp.getLongitude() + ",";
                    result += "\"lat\":" + temp.getLatitude() + ",";
                    result += "\"altitude\":\""
                            + Double.parseDouble(temp.getAltitude().toString() == "" ? "0" : temp.getAltitude().toString()) + "\"";
                    result += "},";
                }
                if (result.endsWith(","))
                    result = result.subSequence(0, result.length() - 1) + "],\"status\": true}";
                else
                    result = result + "],\"status\": true}";
            }
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return result;
    }

    /****
     * 乡镇预报
     * @param newestDate
     * @param county
     * @return
     */
    @Override
    public List<TownshipForecast> getTownshipFcst(TownshipForecastKey newestDate, String county) {
        List<TownshipForecast> resultList = new ArrayList<TownshipForecast>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");
        columns.add("StationName");
        columns.add("longitude");
        columns.add("latitude");
        columns.add("CAST(replace(cast(humid AS VARCHAR),'-65535','99999') as numeric(18,1)) as humid");
        columns.add("to_char(datechar, 'yyyy-MM-dd HH24:MI:SS') as dateChar");
        columns.add("NTimes");
        columns.add("weather1");
        columns.add("CAST(replace(cast(maxtemp AS VARCHAR),'-65535','99999') as numeric(18,1)) as maxtemp");
        columns.add("CAST(replace(cast(minTemp AS VARCHAR),'-65535','99999') as numeric(18,1)) as minTemp");
        columns.add("winds");
        columns.add("windd");
        columns.add("rain");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (!StringUtil.IsNullOrEmpty(newestDate.getStationID())) {
            whereCount++;
            strWhere.append(String.format("stationid='%s'", newestDate.getStationID()));
        }
        if (newestDate.getDateChar() != null) {
            strWhere.append(String.format(" and datechar='%tF'", newestDate.getDateChar()));
        }
        if (!StringUtil.IsNullOrEmpty(newestDate.getTimeChar())) {
            strWhere.append(String.format(" and timechar='%s'", newestDate.getTimeChar()));
        }
        if (newestDate.getNTimes() != null && newestDate.getNTimes() > 0) {
            strWhere.append(String.format(" and ntimes<='%d' and ntimes >'%d'", newestDate.getNTimes(),
                    newestDate.getNTimes() - 24));
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        strWhere.append(String.format(" and city like '%s%%'", DbConfig.CITY));
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"datechar desc", "StationID ASC", "NTimes ASC"});
        try {
            if (DateTime.UserMainDataTable(newestDate.getDateChar(), DbConfig.CACHEDAYS)) {
                selectParam.put("method", "township_forecast_province");
            } else {
                selectParam.put("method", "township_forecast_provincetemp");
            }
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<TownshipForecast>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        return resultList;
    }



    /***
     * 得到灾点查询
     * @param selectKey
     * @param type
     * @return
     */
    @Override
    public Object getDPoint(potential_points selectKey, String type) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (!StringUtil.IsNullOrEmpty(selectKey.getCounty())) {
            strWhere.append(String.format(" and county='%s'", selectKey.getCounty()));
        }
        if (!StringUtil.IsNullOrEmpty(selectKey.getPp_name())) {
            strWhere.append(" and pp_name like '%" + selectKey.getPp_name() + "%'");
        }
        if (!StringUtil.IsNullOrEmpty(selectKey.getLon()) && !StringUtil.IsNullOrEmpty(selectKey.getLat())) {
            selectRequest.setColumns(new String[]{"*", String.format(" cast( GetDistance(cast(lon as float8),cast(lat as float8),cast('%s' as float8),cast('%s' as float8)) as numeric(18,1)) as dis_vol", selectKey.getLon(), selectKey.getLat())});
            selectRequest.setLimit(10);
            selectRequest.setSort(new String[]{String.format(" cast( GetDistance(cast(lon as float8),cast(lat as float8),cast('%s' as float8),cast('%s' as float8)) as numeric(18,1))", selectKey.getLon(), selectKey.getLat())});
            strWhere.append(" and  dis_type in ('崩塌','泥石流','滑坡')");
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            List<potential_points> listData1 = new ArrayList<potential_points>();
            selectParam.put("method", "potential_points");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            listData1 = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<potential_points>>() {
            });
            if (listData1.equals("[]")) {
                return null;
            } else {
                return new ResultObj("查询成功", listData1, true);
            }
        } catch (Exception e) {
            // TODO: handle exception
            return new ResultObj("查询失败", e.getMessage(), false);
        }
    }

    /***
     * 雨量站
     * @param elemQuery
     * @return
     */
    @Override
    public List<ActualData> slElementQuery(ActualElemQuery elemQuery) {
        String result = "";
        List<ActualData> list = new ArrayList<ActualData>();
        List<water_rain> rainlist = new ArrayList<water_rain>();
        String starttime = new DateTime(elemQuery.getStartDate()).toDateTimeString();
        String endtime = new DateTime(elemQuery.getEndDate()).toDateTimeString();
        String pos = "all";
        try {
            Map<String, String> Stamap = new HashMap<String, String>();   //雨量站点映射表
            //初始化雨量站点信息
            RequestDataBySelect dataBySelect = new RequestDataBySelect();
            List<String> columns = new ArrayList<String>();
            Map<String, String> map = new HashMap<String, String>();
            columns.add("stcd");
            columns.add("stnm");
            columns.add("lgtd");
            columns.add("lttd");
            dataBySelect.setColumns(columns.toArray(new String[columns.size()]));
            dataBySelect.setParam("addvcd = '"+DbConfig.advCode+"' and sttp like 'P%'");
            map = new HashMap<String, String>();
            map.put("method", "water_station");
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("sqlType", "select");
            result = pc.processRequest(map);
            List<water_station> rainStalist = new ArrayList<water_station>();
            rainStalist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<water_station>>() {
            });
            if (rainStalist.size() > 0) {
                for (int i = 0; i < rainStalist.size(); i++) {
                    Stamap.put(rainStalist.get(i).getStcd(), rainStalist.get(i).getStnm() + ";" + rainStalist.get(i).getLgtd() + ";" + rainStalist.get(i).getLttd());
                }
            }
            //查询雨量站的实况信息
            dataBySelect = new RequestDataBySelect();
            columns = new ArrayList<String>();
            columns.add("stcd");
            columns.add("sum(drp) as drp");
            dataBySelect.setSort(new String[]{"drp desc"});
            dataBySelect.setParam(String.format(" tm>='%s' and tm<='%s'",
                    starttime, endtime));
            dataBySelect.setColumns(columns.toArray(new String[columns.size()]));
            map = new HashMap<String, String>();
            map.put("method", "water_rain");
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("sqlType", "select");
            result = pc.processRequest(map);
            if (result.equals("")) {
                result = "[]";
            }
            rainlist = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<water_rain>>() {
            });
            for (water_rain ai : rainlist) {
                ActualData ac = new ActualData();
                ac.setRain(ai.getDrp());
                ac.setType("water");
                list.add(ac);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /****
     * 颜色分级
     * @param elementType
     * @return
     */
    @Override
    public List<ElemContourSet> getElemContourSet(String elementType) {
        List<contour_setting> dataList = new ArrayList<contour_setting>();
        List<ElemContourSet> resultList = new ArrayList<ElemContourSet>();
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            selectRequest.setSort(new String[]{"elementvalue"});
            selectRequest.setParam(String.format("ElementType='%s'", elementType));
            selectParam.put("method", "contour_setting");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<contour_setting>>() {
            });
            // 赋值
            if (dataList.size() > 0) {
                for (contour_setting setting : dataList) {
                    ElemContourSet elemSet = new ElemContourSet();
                    elemSet.setElementColor(setting.getElementcolor());
                    elemSet.setElementValue(setting.getElementvalue());
                    elemSet.setElemrntInstruction(setting.getElemrntinstruction());
                    resultList.add(elemSet);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }

    /***
     * 水情
     * @param startDate
     * @param endDate
     * @param countys
     * @return
     */
    @Override
    public Object waterQuery(Date startDate, Date endDate, String countys) {
        List<water_station> dataList = new ArrayList<water_station>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("lgtd");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns.add("stnm");
        columns.add("lttd");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        selectRequest.setParam("addvcd like'" + DbConfig.advCode.substring(0, 4) + "%' and (sttp='ZQ' or sttp='ZZ')");
        try {
            selectParam.put("method", "water_station");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water_station>>() {
            });
            if (dataList != null && dataList.size() > 0) {
                for (water_station w : dataList) {
                    List<water> dataList1 = new ArrayList<water>();
                    selectParam = new HashMap<String, String>();
                    selectRequest = new RequestDataBySelect();
                    // 获取查询字段
                    columns = new ArrayList<String>();
                    columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
                    columns.add("stationname");
                    columns.add("latestobservetime");
                    columns.add("smallscalewaterstatus");
                    selectRequest.setColumns(columns.toArray(new String[columns.size()]));
                    // 拼接where字段
                    StringBuilder strWhere = new StringBuilder();
                    int whereCount = 0;
                    if (startDate != null) {
                        whereCount++;
                        strWhere.append(String.format("latestobservetime >='%tF %tT'", startDate, startDate));
                    }
                    if (endDate != null) {
                        strWhere.append(String.format(" and latestobservetime <='%tF %tT'", endDate, endDate));
                    }
                    strWhere.append(" and stationname = '" + w.getStnm().trim() + "'");
                    if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
                        strWhere = strWhere.replace(0, 4, "");
                    }
                    selectRequest.setParam(strWhere.toString());
                    selectRequest.setSort(new String[]{"latestobservetime desc"});
                    try {
                        selectParam.put("method", "water");
                        selectParam.put("sqlType", "select");
                        selectParam.put("param", JsonUtil.object2Json(selectRequest));
                        message = pc.processRequest(selectParam);
                        dataList1 = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water>>() {
                        });
                        w.setStnm(w.getStnm().trim());
                        w.setLon(w.getLgtd());
                        w.setLat(w.getLttd());
                        w.setBsnm("0");
                        if (dataList1 != null && dataList1.size() > 0) {
                            for (water sta : dataList1) {
                                w.setTime(new DateTime(sta.getLatestobservetime()).toDateTimeString());
                                w.setStationid(sta.getStationid());
                                w.setBsnm(sta.getSmallscalewaterstatus().toString());
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        System.err.println(e.getStackTrace());
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", dataList, true);
    }



    /***
     * 河道水位监控
     * @return
     */
    @Override
    public Object getRiverWarnMoniInfo() {
        String result = "";
        DateTime currentTime = DateTime.now();
        String strDate1 = currentTime.AddDays(-1).toDateTimeString(); // 开始时间
        String strDate2 = currentTime.toDateTimeString(); // 开始时间
        List<water> infos = new ArrayList<water>();

        RequestDataBySelect dataBySelect = new RequestDataBySelect();
        Map<String, String> map = new HashMap<String, String>();
        dataBySelect.setParam("latestobservetime between '" + strDate1 + "' and '" + strDate2 + "' and location like '%"+DbConfig.CITY+"%' and  smallscalewaterstatus > warningwaterstatus");
        dataBySelect.setSort(new String[]{"latestobservetime desc"});
        try {
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "water");
            map.put("sqlType", "select");
            result = pc.processRequest(map);
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            } else {
                infos = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<water>>() {
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", infos, true);
    }

    /***
     * 超警戒水位查询
     * @param stationname
     * @return
     */
    @Override
    public Object getWaterWarnMoniInfo(String stationname) {
        String result = "";
        DateTime currentTime = DateTime.now();
        String strDate1 = currentTime.AddDays(-1).toDateTimeString(); // 开始时间
        String strDate2 = currentTime.toDateTimeString(); // 开始时间
        List<reservoir_water_info> infos = new ArrayList<reservoir_water_info>();

        RequestDataBySelect dataBySelect = new RequestDataBySelect();
        Map<String, String> map = new HashMap<String, String>();
        dataBySelect.setParam("observtime between '" + strDate1 + "' and '" + strDate2 + "' and 1 = 1 and  waterlevel > limited_waterlv");
        if (!StringUtil.IsNullOrEmpty(stationname)) {
            dataBySelect.setParam(dataBySelect.getParam().replace("1=1", "stationname LIKE '%" + stationname + "%'"));
        }
        dataBySelect.setSort(new String[]{"observtime desc"});
        try {
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "reservoir_water_info");
            map.put("sqlType", "select");
            map.put("advCode", DbConfig.advCode);
            result = pc.processRequest(map);
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            } else {
                infos = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<reservoir_water_info>>() {
                });
                for (reservoir_water_info info : infos)
                    info.setWaterflow((float) (info.getWaterlevel() - info.getLimited_waterlv()));
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", infos, true);
    }



    /****
     * 获取预警信号  当天
     * @return
     */
    @Override
    public Object getWarnSignalInfo() {
        String result = "";
        try {
            String yjLevel = "";
            String color = "";
            DateTime currentTime = DateTime.now();
            String strDate1 = currentTime.AddDays(-1).toDateTimeString(); // 开始时间
            String strDate2 = currentTime.toDateTimeString(); // 开始时间
            String type = ""; // 类型
            String level = ""; // 级别
            String bFree = "0"; // 是否解除

            RequestDataBySelect dataBySelect = new RequestDataBySelect();
            dataBySelect.setParam("AnnouncedTime BETWEEN '" + strDate1 + "' AND '" + strDate2 + "' AND 1=1 AND 2=2 AND 3=3");

            dataBySelect.setParam(dataBySelect.getParam().replace("1=1", "type in ('暴雨','暴雪','强对流','高温')"));
            if (!StringUtil.IsNullOrEmpty(level) && !level.equals("全部")) {
                dataBySelect.setParam(dataBySelect.getParam().replace("2=2", "Color LIKE '%" + level + "%'"));
            }
            if (!StringUtil.IsNullOrEmpty(bFree)) {
                dataBySelect.setParam(dataBySelect.getParam().replace("3=3", "bFree='" + bFree + "'"));
            }
            dataBySelect.setSort(new String[]{"AnnouncedTime DESC"});
            Map<String, String> map = new HashMap<String, String>();
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "warn_signal_info");
            map.put("sqlType", "select");
            map.put("advCode", DbConfig.advCode);
            result = pc.processRequest(map);
            if (result.equals("")) {
                result = "[]";
            }

            List<warn_signal_info> infos = new ArrayList<warn_signal_info>();
            infos = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<warn_signal_info>>() {
            });

            // 执行查询

            result = "{\"message\": \"查询成功\",\n" +
                    "\"data\": [";
            if (infos != null && infos.size() > 0) {
                for (warn_signal_info info : infos) {
                    result += "{";
                    result += "\"id\":\"" + info.getId() + "\",";
                    result += "\"area\":\"" + info.getArea() + "\",";
                    result += "\"type\":\"" + info.getType() + "\",";//
                    yjLevel = info.getColor();
                    switch (yjLevel) {
                        case "红色":
                            color = "255";
                            break;
                        case "橙色":
                            color = "42495";
                            break;
                        case "黄色":
                            color = "65535";
                            break;
                        case "蓝色":
                            color = "16711680";
                            break;
                    }
                    result += "\"level\":\"" + yjLevel + "\",";
                    result += "\"color\":\"" + color + "\",";
                    result += "\"county\":\"" + info.getCounty() + "\",";
                    result += "\"standard\":\"" + info.getStandard() + "\",";
                    result += "\"defenseGuide\":\"" + info.getDefenseguide() + "\",";
                    result += "\"announcedTime\":\"" +info.getAnnouncedtime() + "\",";
                    result += "\"signatory\":\"" + info.getSignatory() + "\",";
                    result += "\"watch\":\"" + info.getWatch() + "\",";
                    result += "\"pos\":\"" + info.getPos() + "\",";
                    result += "\"bFree\":\"" + info.getBfree() + "\",";
                    result += "\"jcpath\":\"" + info.getJcpath() + "\",";
                    result += "\"y2path\":\"" + info.getY2path() + "\",";
                    result += "\"pos\":\"" + info.getPos() + "\",";
                    result += "\"jb\":\"" + Integer.parseInt(info.getJb().toString()) + "\"";
                    result += "},";
                }
                if (result.endsWith(","))
                    result = result.subSequence(0, result.length() - 1) + "],\"status\": true}";
                else
                    result = result + "],\"status\": true}";
            } else {
                return new ResultObj("查询成功", "[]", true);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return result;
    }


    /***
     * 飞行路线
     * @param request
     * @return
     */
    @Override
    public Object getFlypath(HttpServletRequest request) {
        String reservoirid = request.getParameter("reservoirid");
        List<fly_path> list = new ArrayList<>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        if (!StringUtil.IsNullOrEmpty(reservoirid))
            selectRequest.setParam("reservoirid = '" + reservoirid + "'");
        try {
            selectParam.put("method", "fly_path");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            list = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<fly_path>>() {
            });
            for (fly_path path : list) {
                String result = "\"geometry\": {\"type\": \"LineString\",\"coordinates\": [";
                String[] poss = path.getPos().split("\\*");
                for (String po : poss) {
                    String lon = po.split(",")[0];
                    String lat = po.split(",")[1];
                    result += "[" + Double.parseDouble(lon) + "," + Double.parseDouble(lat) + "],";
                }
                if (result.endsWith(","))
                    result = result.substring(0, result.length() - 1) + "]}";
                else result += "]}";
                path.setPos(result);
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", list, true);
    }


    /****
     * 获取云图   最新一张
     * @param request
     * @return
     */
    @Override
    public Object getNewestSatelliteNephoram(HttpServletRequest request) {
        String result = "";
        String strtype = request.getParameter("yttype");
        if (StringUtil.IsNullOrEmpty(strtype))
            strtype = "FY2E红外图像";
        List<satellitenephoram> infos = new ArrayList<satellitenephoram>();

        RequestDataBySelect dataBySelect = new RequestDataBySelect();
        Map<String, String> map = new HashMap<String, String>();
        dataBySelect.setParam("1=1");
        dataBySelect.setParam(dataBySelect.getParam().replace("1=1", "ytType ='" + strtype + "'"));
        dataBySelect.setSort(new String[]{"DateChar desc,TimeChar desc"});
        dataBySelect.setLimit(1);
        try {
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "satellitenephoram");
            map.put("sqlType", "select");
            result = pc.processRequest(map);
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            } else {
                infos = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<satellitenephoram>>() {
                });
                for (satellitenephoram sl : infos) {
                    String fileName = "yt_png_file" + "_" + new DateTime(sl.getDatechar()).toDateTimeString("yyyy-MM-dd") + "_" + sl.getTimechar().trim() + "_" + sl.getYttype().trim();
                    String serviceFilePath = "";
                    // 下载
                    fileName = StringUtil.trimEnd(fileName, '_') + ".jpg";
                    String path = request.getContextPath();
                    String basePath = DbConfig.IP + path
                            + "/Temp/File/";
                    String serviceUrl = basePath + fileName;
                    String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\File\\";
                    serviceFilePath = urlpath + fileName;// 服务器文件
                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    // 如果目录中不存在文件，下载雷达文件到temp目录
                    File serviceFile = new File(serviceFilePath);// 服务器文件
                    if (!serviceFile.exists()) {// 把文件上传到服务器{
                        Map<String, Object> queryMap = new HashMap<String, Object>();
                        queryMap.put("datechar", new DateTime(sl.getDatechar()).toDateTimeString("yyyy-MM-dd").trim());
                        queryMap.put("timechar", sl.getTimechar().trim());
                        queryMap.put("yttype", sl.getYttype().trim());
                        queryMap.put("collectionName", "yt_png_file");
                        byte[] data = ms.selectData(queryMap);
                        if (data == null) {
                            serviceFilePath = "";
                        } else {
                            FileUtil.bytesToFile(data, serviceFilePath);
                        }
                    }
                    if (!serviceFilePath.equals("")) {
                        serviceFilePath = serviceUrl;
                    }
                    String imagepath = serviceFilePath;
                    sl.setJwimgpath(imagepath);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", infos, true);
    }


    /****
     * 获取雷达图   最新一张
     * @param request
     * @return
     */
    @Override
    public Object getNewestDoppler(HttpServletRequest request) {
        String result = "";
        List<doppler> infos = new ArrayList<doppler>();

        RequestDataBySelect dataBySelect = new RequestDataBySelect();
        Map<String, String> map = new HashMap<String, String>();
        dataBySelect.setParam("1=1  and 2=2 and 3=3  and state='1'");
        dataBySelect.setParam(dataBySelect.getParam().replace("1=1", "ldType ='"+DbConfig.ldtype+"'"));
        dataBySelect.setParam(dataBySelect.getParam().replace("2=2", "StationId ='"+DbConfig.radarid+"'"));//后续需要改qxy
        dataBySelect.setParam(dataBySelect.getParam().replace("3=3", "Elevation ='"+DbConfig.elevation+"'"));
        dataBySelect.setSort(new String[]{"DateChar desc,TimeChar desc"});
        dataBySelect.setLimit(1);
        try {
            map.put("param", JsonUtil.object2Json(dataBySelect));
            map.put("method", "doppler");
            map.put("sqlType", "select");
            result = pc.processRequest(map);
            if (result.equals("")) {
                return new ResultObj("查询成功", "[]", true);
            } else {
                infos = JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<doppler>>() {
                });
                for (doppler sl : infos) {
                    String fileName = "ld_png_jw_file" + "_" + new DateTime(sl.getDatechar()).toDateTimeString("yyyy-MM-dd") + "_" + sl.getTimechar().trim() + "_19_0";
                    String serviceFilePath = "";
                    // 下载
                    fileName = StringUtil.trimEnd(fileName, '_') + ".jpg";
                    String path = request.getContextPath();
                    String basePath = DbConfig.IP + path
                            + "/Temp/File/";
                    String serviceUrl = basePath + fileName;
                    String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\File\\";
                    serviceFilePath = urlpath + fileName;// 服务器文件
                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    // 如果目录中不存在文件，下载雷达文件到temp目录
                    File serviceFile = new File(serviceFilePath);// 服务器文件
                    if (!serviceFile.exists()) {// 把文件上传到服务器{
                        Map<String, Object> queryMap = new HashMap<String, Object>();
                        queryMap.put("stationid", ""+DbConfig.radarid+"");
                        queryMap.put("datechar", new DateTime(sl.getDatechar()).toDateTimeString("yyyy-MM-dd"));
                        queryMap.put("timechar", sl.getTimechar().trim());
                        queryMap.put("ldtype", DbConfig.ldtype);
                        queryMap.put("elevation", DbConfig.elevation);
                        queryMap.put("collectionName", "ld_png_file");
                        byte[] data = ms.selectData(queryMap);
                        if (data == null) {
                            serviceFilePath = "";
                        } else {
                            FileUtil.bytesToFile(data, serviceFilePath);
                        }
                    }
                    if (!serviceFilePath.equals("")) {
                        serviceFilePath = serviceUrl;
                    }
                    String imagepath = serviceFilePath;
                    sl.setJwimgpath(imagepath);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", infos, true);
    }


}
